package com.tiantianyuegou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.adapter.GoodListAdapter;
import com.tiantianyuegou.fragment.FenLeiFragment;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.model.GoodsModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 商品列表界面
 * Created by huyang on 2016/1/7 0007.
 */
public class GoodsListActivity extends BaseActivity implements View.OnClickListener {
//     http://hjtech.wicp.net:8080/tiantianyuegou-api/product/search?keywords=红酒&page=1&sort=1&order=2
    private TextView tv_search;
    private ImageView back;
    private PullToRefreshGridView refresh;
    private String TAG = "GoodsListActivity";
    private List<GoodsModel> data;
    private GoodListAdapter mAdapter;
    private LoadingDialog loading;
    private TextView tv_default, tv_price, tv_sales, tv_newest,tv_fenlei;
    private ImageView iv_top, iv_down;
    private String keyWords = "";//关键字
    private String type;
    private String pcAllId;//点击全部时传过来的分类id
    private String pcid;
    private String sord = "sales";
    private String order = "desc";
    private int page = 0;//分页
    private boolean isRefresh = true;
    private boolean isLoadMore = false;
    private int TYPE;
    private FrameLayout layout_nogoods;
    private boolean isTop = true;//true为降序，false为升序


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodslist);
       Tools.changeSystemBar(this);
        getData();
        initViews();
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    public void findViewByIds() {
        tv_search = (TextView) findViewById(R.id.tv_search);
        back = (ImageView) findViewById(R.id.iv_back);
        refresh = (PullToRefreshGridView) findViewById(R.id.refresh);
        tv_default = (TextView) findViewById(R.id.tv_default);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_sales = (TextView) findViewById(R.id.tv_salenum);
        tv_newest = (TextView) findViewById(R.id.tv_newest);
        tv_fenlei = (TextView) findViewById(R.id.tv_fenlei);
        layout_nogoods = (FrameLayout) findViewById(R.id.layout_nogoods);
        layout_nogoods.setVisibility(View.GONE);
        iv_top = (ImageView) findViewById(R.id.iv_top);
        iv_down = (ImageView) findViewById(R.id.iv_down);
        tv_default.setTextColor(getResources().getColor(R.color.textcolor_red));
        tv_price.setTextColor(getResources().getColor(R.color.textcolor_black));
        tv_sales.setTextColor(getResources().getColor(R.color.textcolor_black));
        tv_newest.setTextColor(getResources().getColor(R.color.textcolor_black));
        tv_fenlei.setTextColor(getResources().getColor(R.color.textcolor_black));
//      TODO 需要真正替换的
        refresh = (PullToRefreshGridView) findViewById(R.id.refresh);

        //下拉刷新
        ILoadingLayout pullDownRefresh = refresh.getLoadingLayoutProxy(true, false);
        pullDownRefresh.setPullLabel("下拉刷新");//下拉提示
        pullDownRefresh.setRefreshingLabel("正在刷新...");//刷新提示
        pullDownRefresh.setReleaseLabel("松开刷新");//下拉一定距离显示的提示
        //上拉加载
        ILoadingLayout pullUpRefresh = refresh.getLoadingLayoutProxy(false, true);
        pullUpRefresh.setPullLabel("上拉加载");
        pullUpRefresh.setRefreshingLabel("正在刷新...");
        pullUpRefresh.setReleaseLabel("松开加载更多");
    }

    @Override
    public void initListener() {
        data = new ArrayList<>();
        mAdapter = new GoodListAdapter(this);
        refresh.setAdapter(mAdapter);
        loading = new LoadingDialog(this);
        tv_search.setOnClickListener(this);
        tv_default.setOnClickListener(this);
        tv_newest.setOnClickListener(this);
        tv_price.setOnClickListener(this);
        tv_sales.setOnClickListener(this);
        tv_fenlei.setOnClickListener(this);
        back.setOnClickListener(this);
        refresh.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(GoodsListActivity.this, GoodsDetailActivity.class);
//                将商品id与用户id进行传递，   传递商品id与用户id进行传递到详情界面，商品价格，累计销售，库存，积分抵用，
                String tpId = data.get(i).getTpId();
                String tpPic = data.get(i).getGoodsPhoto();
                intent.putExtra("tgId", tpId);
                intent.putExtra("tpPic", tpPic);
                intent.putExtra("type", "GoodsListActivity");
                Log.e(TAG, "传递的数据是" + tpId + tpPic + "=======");
                startActivity(intent);
            }
        });
        refresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                //下拉刷新
                page = 0;
                initData();
                isRefresh = true;
                isLoadMore = false;
                String label = DateUtils.formatDateTime(
                        getApplicationContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                //上拉加载
                initData();
                isRefresh = false;
                isLoadMore = true;
                String label = DateUtils.formatDateTime(
                        getApplicationContext(),
                        System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME
                                | DateUtils.FORMAT_SHOW_DATE
                                | DateUtils.FORMAT_ABBREV_ALL);
                refresh.getLoadingLayoutProxy().setLastUpdatedLabel(label);
            }
        });
    }

    public void getData() {
        //    http://hjtech.wicp.net:8080/tiantianyuegou-api/product/search?keywords=红酒&page=1&sort=1&order=2
        Intent intent = getIntent();
        pcAllId = intent.getStringExtra("pcAllId");
        pcid = intent.getStringExtra("pcid");
        type = intent.getStringExtra("type");
        keyWords = intent.getStringExtra("keyWords");
        keyWords = getIntent().getStringExtra("keyWords");
        System.out.println("---------------" + keyWords + "---------------");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //将用户搜索的内容显示出来
        if (keyWords != null && !"".equals(keyWords)) {
            tv_search.setText(keyWords);
            //data.clear();
        }
    }

    @Override
    public void initData() {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查网络");
        }

        loading.showDialog();
        loading.setMsg("正在加载");
        RequestParams params = new RequestParams();
//        http://hjtech.wicp.net:8080/tiantianyuegou-api/product/search?keywords=红酒&page=1&sort=1&order=2
//        params.addBodyParameter("keywords","红酒");
        params.addBodyParameter("page",1+"");//页码
        params.addBodyParameter("sort",1+"");//排序
        params.addBodyParameter("order",2+"");//排序字段默认的为""

//        params.addBodyParameter("sord", sord);
//        params.addBodyParameter("order", order);
//        params.addBodyParameter("page", (++page) + "");
//        params.addBodyParameter("page", (++page) + "");

//        if (pcAllId != null && !"".equals(pcAllId)) {
//            params.addBodyParameter("pcAllId", pcAllId);
//        }
//        if (pcid != null && !"".equals(pcid)) {
//            params.addBodyParameter("pcid", pcid);
//        }
//        if (type != null && !"".equals(type)) {
//            params.addBodyParameter("type", type);
//        }
        if (keyWords != null && !"".equals(keyWords)) {
            params.addQueryStringParameter("keywords", keyWords);
        }


//        Log.e("TAG数据是=========", "params: "+ ":page:" + page + ":pcAllID:" + pcAllId + ":pcId:" + pcid +
//                ":type:" + type + ":keyword:" + keyWords);

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.SEARCH, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loading.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取商品列表失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            layout_nogoods.setVisibility(View.GONE);
                            JSONArray list = jsonObject.getJSONArray("list");
                            if (isRefresh) {
                                data.clear();
                                isRefresh = false;
                            } else if (isLoadMore) {
                                isLoadMore = false;
                            }

                            for (int i = 0; i < list.length(); i++) {
                                GoodsModel model = new GoodsModel();
                                JSONObject temp = list.getJSONObject(i);

                                String tgId = temp.getString("tg_id");//商品id
                                String name = temp.getString("tg_name");//商品名称
                                String price = temp.getString("tg_price");//商品价格
                                String redBag = temp.getString("tg_number");
//                                String tpName = temp.getString("tpName");
//                                String tpSalePrice = temp.getString("tpSalePrice");
//                                String tpSalesCount = temp.getString("tpSalesCount");
//                                String tpPic = temp.getString("tpPic");
//                                String tpId = temp.getString("tpId");
                                String photo = temp.getString("tg_simple_pic");
                                Log.e("解析成功，解析的"+TAG, "解析成功，解析到达 数据是"+tgId.toString()+"========" + name.toString()+"=======" + price.toString()+"=======" + redBag .toString()+ photo.toString());
                                if (photo.contains(",")) {
                                    String pic = photo.substring(0, photo.indexOf(","));
                                    model.setGoodsPhoto(pic);
                                } else {
                                    model.setGoodsPhoto(photo);
                                }
                                model.setGoodsName(name);//商品明名称
                                model.setGoodsPrice(price);//商品价格
                                model.setRedBagCount(redBag);
                                model.setTpId(tgId);
                                data.add(model);
                            }
                            if (data.size() == 0) {
                                layout_nogoods.setVisibility(View.VISIBLE);
                            }
                            mAdapter.setData(data);
                            mAdapter.notifyDataSetChanged();

                        } else {

                            if (code.equalsIgnoreCase("105")) {
                                if (!isLoadMore) {
                                    // showMsg("暂无商品");
                                    layout_nogoods.setVisibility(View.VISIBLE);
                                    data.clear();
                                    mAdapter.setData(data);
                                    mAdapter.notifyDataSetChanged();
                                }

                                if (isLoadMore && data.size() > 0) {
                                    isLoadMore = false;
                                    page--;
                                    showMsg("没有更多商品");
                                } else {
                                    showMsg("暂无商品");
                                    layout_nogoods.setVisibility(View.VISIBLE);
                                    data.clear();
                                    mAdapter.setData(data);
                                    mAdapter.notifyDataSetChanged();
                                }
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        refresh.onRefreshComplete();
                        layout_nogoods.setVisibility(View.VISIBLE);
                        if (isRefresh) {
                            isRefresh = false;
                        } else if (isLoadMore) {
                            isLoadMore = false;
                            page--;
                        }
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loading.dismiss();
                refresh.onRefreshComplete();
                showMsg("当前网络不可用，请检查网络");
                layout_nogoods.setVisibility(View.VISIBLE);
                if (isRefresh) {
                    isRefresh = false;
                } else if (isLoadMore) {
                    isLoadMore = false;
                    page--;
                }
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            keyWords = data.getStringExtra("keyWords");
            //System.out.println("------keyWord=" + keyWord);
            initData();

        }
    }

    @Override
    public void onClick(View view) {
        page = 0;
        isRefresh = true;
        isLoadMore = true;
        switch (view.getId()) {
            case R.id.tv_search:
                Intent search = new Intent(GoodsListActivity.this, SearchActivity.class);
                startActivityForResult(search, 1001);
                break;
            case R.id.iv_back:
                finish();
                break;
//            默认
            case R.id.tv_default:
//           http://hjtech.wicp.net:8080/tiantianyuegou-api/product/search?keywords=红酒&page=1&sort=1order=2
                tv_default.setTextColor(getResources().getColor(R.color.textcolor_red));
                tv_price.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_sales.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_newest.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_fenlei.setTextColor(getResources().getColor(R.color.textcolor_black));


                sord = 1+"";
                order = "";
                initData();
                break;
//            价格
            case R.id.tv_price:
                tv_default.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_price.setTextColor(getResources().getColor(R.color.textcolor_red));
                tv_sales.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_newest.setTextColor(getResources().getColor(R.color.textcolor_black));
//                params.addBodyParameter("keywords","红酒");
//                params.addBodyParameter("page",1+"");//页码
//                params.addBodyParameter("sort",1+"");//排序
//                params.addBodyParameter("order",2+"");//排序字段默认的为""
                sord =1+"";
                order = 1 + "";
                initData();

                if (isTop) {
                    iv_top.setImageResource(R.mipmap.top2);
                    iv_down.setImageResource(R.mipmap.down);
                    order = 1+"";
                    isTop = false;
                } else {
                    iv_down.setImageResource(R.mipmap.down2);
                    iv_top.setImageResource(R.mipmap.top);
                    isTop = true;
                    order = 2+"";
                }
                break;
//            销量
            case R.id.tv_salenum:
//                iv_top.setImageResource(R.mipmap.top);
//                iv_down.setImageResource(R.mipmap.down);
                tv_default.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_price.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_sales.setTextColor(getResources().getColor(R.color.textcolor_red));
                tv_newest.setTextColor(getResources().getColor(R.color.textcolor_black));

                sord = 1+"";
                order = 3+"";
                initData();

                break;
//            最新
            case R.id.tv_newest:
//                iv_top.setImageResource(R.mipmap.top);
//                iv_down.setImageResource(R.mipmap.down);
                tv_default.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_price.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_sales.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_fenlei.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_newest.setTextColor(getResources().getColor(R.color.textcolor_red));


                sord = 1+"";
                order = 1 + "";
                initData();

                break;
//            分类
            case R.id.tv_fenlei:
                tv_default.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_price.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_sales.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_newest.setTextColor(getResources().getColor(R.color.textcolor_black));
                tv_fenlei.setTextColor(getResources().getColor(R.color.textcolor_red));
//                initData();
//                切换到分类界面
                getSupportFragmentManager().beginTransaction().replace(R.id.layout_nogoods, new FenLeiFragment()).commit();
                break;
            default:
                break;
        }
    }
}
